package com.hs;

import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: hs
 * @Description:
 * @Date: Create in 14:31 2019/4/22
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest();
        ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
        RWDictionary rwDictionary = readWriteLockTest.new RWDictionary(readWriteLock);
        ExecutorService executorService = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(40));

        for (int i = 0; i <40; i++) {
            executorService.execute(rwDictionary);
        }
        executorService.shutdown();
    }

    public class RWDictionary extends  Thread{
        private final Map<String, String> m = new TreeMap<>();
        private ReentrantReadWriteLock rwl;
        private Lock r;
        private Lock w;
        Random random = new Random();
        public RWDictionary(ReentrantReadWriteLock rwl){
            this.rwl = rwl;
            this.r = rwl.readLock();
            this.w = rwl.writeLock();
        }
        @Override
        public void run() {
            //int i = random.nextInt();
            String key = "key";
            get(key);

            put(key,key);
            System.out.println(get(key));
            clear(key);

        }

        public String get(String key) {
            r.lock();
            try {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return m.get(key);
            } finally {
                r.unlock();
            }
        }

        public String[] allKeys() {
            r.lock();
            try {
                String[] a = new String[m.size()];
                return m.keySet().toArray(a);
            } finally {
                r.unlock();
            }
        }

        public String put(String key, String value) {
            w.lock();
            try {
                return m.put(key, value);
            } finally {
                w.unlock();
            }
        }

        public void clear(String key) {
            w.lock();
            try {
                m.remove(key);
                //m.clear();
            } finally {
                w.unlock();
            }
        }
    }
}

